<template>
  <div class="page-container">
    <!-- 搜索区域 -->
    <div class="search-filter">
      <el-form :model="searchForm" inline>
        <el-form-item label="客户名称">
          <el-input v-model="searchForm.customerName" placeholder="请输入客户名称" clearable style="width: 180px" />
        </el-form-item>
        <el-form-item label="问题类型">
          <el-select v-model="searchForm.problemType" placeholder="请选择问题类型" clearable style="width: 180px">
            <el-option v-for="item in questionTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="售后优先级">
          <el-select v-model="searchForm.priority" placeholder="请选择售后优先级" clearable style="width: 180px">
            <el-option v-for="item in priorityOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理状态">
          <el-select v-model="searchForm.status" placeholder="请选择处理状态" clearable style="width: 180px">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格工具栏 -->
    <div class="operation-btns">
      <el-button type="danger" :disabled="!selectedRows.length" @click="handleBatchDelete">批量删除</el-button>
      <el-button type="success" @click="handleExport">导出</el-button>
    </div>

    <!-- 表格区域 -->
    <div class="table-container">
      <el-card class="table-card">
        <el-table
          v-loading="loading"
          :data="tableData"
          border
          row-key="id"
          stripe
          highlight-current-row
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="45" align="center" />
          <el-table-column prop="id" label="ID" width="70" align="center" />
          <el-table-column prop="customerName" label="客户名称" min-width="150" show-overflow-tooltip />
          <el-table-column prop="problemType" label="问题类型" width="100" align="center">
            <template #default="scope">
              <el-tag :type="getProblemTypeTag(scope.row.problemType)">
                {{ getProblemTypeLabel(scope.row.problemType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="priority" label="优先级" width="80" align="center">
            <template #default="scope">
              <el-tag :type="getPriorityTag(scope.row.priority)">
                {{ getPriorityLabel(scope.row.priority) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="处理状态" width="90" align="center">
            <template #default="scope">
              <el-tag :type="getStatusTag(scope.row.status)">
                {{ getStatusLabel(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="satisfactionScore" label="满意度评分" width="200" align="center">
            <template #default="scope">
              <el-rate
                v-if="scope.row.satisfactionScore"
                v-model="scope.row.satisfactionScore"
                disabled
                show-score
                text-color="#ff9900"
                score-template="{value}"
              />
              <span v-else>暂无评分</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" fixed="right" align="center">
            <template #default="scope">
              <el-button v-if="scope.row.status === 0" type="primary" link @click="handleEdit(scope.row)"
                >编辑</el-button
              >
              <el-button
                v-if="scope.row.status === 2 || scope.row.status === 3"
                type="primary"
                link
                @click="handleEdit(scope.row)"
                >删除</el-button
              >
              <el-button v-if="scope.row.status !== 0" type="success" link @click="handleReply(scope.row)"
                >查看回复</el-button
              >
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background
          />
        </div>
      </el-card>
    </div>

    <!-- 售后服务编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="编辑售后服务信息" width="550px" @close="resetForm" destroy-on-close>
      <el-form ref="serviceFormRef" :model="serviceForm" :rules="serviceFormRules" label-width="90px" status-icon>
        <el-form-item label="客户名称" prop="customerName">
          <el-input v-model="serviceForm.customerName" placeholder="客户名称" disabled="true" />
        </el-form-item>
        <el-form-item label="问题类型" prop="problemType">
          <el-select v-model="serviceForm.problemType" placeholder="请选择问题类型" style="width: 100%">
            <el-option
              v-for="option in questionTypeOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="serviceForm.priority" placeholder="请选择优先级" style="width: 100%">
            <el-option
              v-for="option in priorityOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="处理状态" prop="status">
          <el-select v-model="serviceForm.status" placeholder="请选择处理状态" style="width: 100%">
            <el-option
              v-for="option in statusOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="满意度评分" prop="satisfactionScore" v-if="serviceForm.status === 2">
          <el-rate
            v-model="serviceForm.satisfactionScore"
            show-score
            text-color="#ff9900"
            score-template="{value}"
            :max="5"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 投诉回复对话框 -->
    <el-dialog v-model="replyDialogVisible" title="投诉回复" width="650px" destroy-on-close>
      <el-form ref="replyFormRef" :model="replyForm" :rules="replyFormRules" label-width="100px" status-icon>
        <el-form-item label="售后服务ID" prop="afterSalesId">
          <el-input v-model="replyForm.afterSalesId" disabled />
        </el-form-item>
        <el-form-item label="投诉内容" prop="complaintContent">
          <el-input
            v-model="replyForm.complaintContent"
            type="textarea"
            :rows="3"
            placeholder="请输入投诉内容"
            :disabled="replyForm.id !== null"
          />
        </el-form-item>
        <el-form-item label="回复内容" prop="replyContent">
          <el-input
            v-model="replyForm.replyContent"
            type="textarea"
            :rows="3"
            placeholder="请输入回复内容"
            :disabled="replyForm.id !== null && replyForm.replyContent"
          />
        </el-form-item>
        <el-form-item label="回复时间" prop="replyTime" v-if="replyForm.replyTime">
          <el-input v-model="replyForm.replyTime" disabled />
        </el-form-item>
        <el-form-item label="满意度评分" prop="satisfactionLevel" v-if="replyForm.id !== null">
          <el-rate
            v-model="replyForm.satisfactionLevel"
            show-score
            text-color="#ff9900"
            score-template="{value}"
            :max="5"
            :disabled="replyForm.satisfactionLevel > 0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="replyDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="submitReply" v-if="!replyForm.id || !replyForm.replyContent"
            >提交回复</el-button
          >
          <el-button
            type="success"
            @click="submitSatisfaction"
            v-if="replyForm.id && replyForm.replyContent && !replyForm.satisfactionLevel"
            >提交评价</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { getAfterSalesRecordsList, updateAfterSalesRecord, deleteAfterSalesRecords } from "@/api/aftersales";
import {
  getComplaintReplyList,
  getComplaintReplyByAfterSales,
  addComplaintReply,
  updateComplaintReply,
  submitSatisfactionRating,
} from "@/api/complaint";
import { getServiceRecordListExcel } from "@/api/export";
import { formatToLocalDateTime } from "@/utils/date";

// 问题类型:1-产品质量,2-安装问题,3-使用咨询,4-维修服务,5-退换货,6-其他
const questionTypeOptions = [
  { value: 1, label: "产品质量", type: "primary" },
  { value: 2, label: "安装问题", type: "success" },
  { value: 3, label: "使用咨询", type: "warning" },
  { value: 4, label: "维修服务", type: "danger" },
  { value: 5, label: "退换货", type: "info" },
  { value: 6, label: "其他", type: "" },
];

// 售后优先级:1-普通,2-紧急
const priorityOptions = [
  { value: 1, label: "普通", type: "" },
  { value: 2, label: "紧急", type: "danger" },
];

// 售后状态:0-待处理,1-处理中,2-已完成,3-已关闭
const statusOptions = [
  { value: 0, label: "待处理", type: "warning" },
  { value: 1, label: "处理中", type: "primary" },
  { value: 2, label: "已完成", type: "success" },
  { value: 3, label: "已关闭", type: "info" },
];

// 搜索表单
const searchForm = reactive({
  customerName: "",
  problemType: "",
  priority: "",
  status: "",
});

// 表格数据
const loading = ref(false);
const tableData = ref([]);
const selectedRows = ref([]);

// 分页
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 售后服务对话框
const dialogVisible = ref(false);
const serviceFormRef = ref(null);
const serviceForm = reactive({
  id: null,
  customerName: "",
  problemType: 1,
  priority: 1,
  status: 0,
  satisfactionScore: 0,
});

// 表单验证规则
const serviceFormRules = {
  customerName: [{ required: true, message: "请输入客户名称", trigger: "blur" }],
  problemType: [{ required: true, message: "请选择问题类型", trigger: "change" }],
  priority: [{ required: true, message: "请选择优先级", trigger: "change" }],
  status: [{ required: true, message: "请选择处理状态", trigger: "change" }],
};

// 投诉回复对话框
const replyDialogVisible = ref(false);
const replyFormRef = ref(null);
const replyForm = reactive({
  id: null,
  afterSalesId: null,
  complaintContent: "",
  replyContent: "",
  replyTime: "",
  satisfactionLevel: 0,
});

// 投诉回复表单验证规则
const replyFormRules = {
  complaintContent: [{ required: true, message: "请输入投诉内容", trigger: "blur" }],
  replyContent: [{ required: true, message: "请输入回复内容", trigger: "blur" }],
};

// 初始化
onMounted(() => {
  fetchRecordsrList();
});

// 获取售后服务列表
const fetchRecordsrList = async () => {
  loading.value = true;

  try {
    const response = await getAfterSalesRecordsList({
      ...searchForm,
      current: pagination.currentPage,
      size: pagination.pageSize,
    });

    if (response.success) {
      pagination.total = response.data.total;
      tableData.value = response.data.list;
    } else {
      tableData.value = [];
      pagination.total = 0;
    }
  } catch (error) {
    console.error("获取售后服务列表失败:", error);
    tableData.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

// 获取问题状态标签类型
const getProblemTypeTag = (problemType) => {
  const option = questionTypeOptions.find((item) => item.value === problemType);
  return option ? option.type : "";
};

// 获取问题状态标签文本
const getProblemTypeLabel = (problemType) => {
  const option = questionTypeOptions.find((item) => item.value === problemType);
  return option ? option.label : "";
};

// 获取优先级标签类型
const getPriorityTag = (priority) => {
  const option = priorityOptions.find((item) => item.value === priority);
  return option ? option.type : "";
};

// 获取优先级标签文本
const getPriorityLabel = (priority) => {
  const option = priorityOptions.find((item) => item.value === priority);
  return option ? option.label : "";
};

// 获取状态标签类型
const getStatusTag = (status) => {
  const option = statusOptions.find((item) => item.value === status);
  return option ? option.type : "";
};

// 获取状态标签文本
const getStatusLabel = (status) => {
  const option = statusOptions.find((item) => item.value === status);
  return option ? option.label : "";
};

// 处理表格选择变化
const handleSelectionChange = (rows) => {
  selectedRows.value = rows;
};

// 处理搜索
const handleSearch = () => {
  pagination.currentPage = 1;
  fetchRecordsrList();
};

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach((key) => {
    searchForm[key] = "";
  });
  handleSearch();
};

// 处理分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  fetchRecordsrList();
};

// 处理当前页变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page;
  fetchRecordsrList();
};

// 新增售后服务
const handleAdd = () => {
  resetForm();
  serviceForm.status = 0; // 默认待处理
  serviceForm.priority = 1; // 默认普通优先级
  serviceForm.problemType = 1; // 默认产品质量
  dialogVisible.value = true;
};

// 编辑售后服务
const handleEdit = (row) => {
  Object.keys(serviceForm).forEach((key) => {
    serviceForm[key] = row[key];
  });
  dialogVisible.value = true;
};

// 处理投诉回复
const handleReply = async (row) => {
  try {
    // 先查询是否已有投诉回复
    const response = await getComplaintReplyByAfterSales(row.id);

    if (response.success && response.data && response.data.length > 0) {
      // 已有投诉回复，加载数据
      const replyData = response.data[0];
      Object.keys(replyForm).forEach((key) => {
        replyForm[key] = replyData[key];
      });
    } else {
      // 没有投诉回复，初始化数据
      resetReplyForm();
      replyForm.afterSalesId = row.id;
    }

    replyDialogVisible.value = true;
  } catch (error) {
    console.error("获取投诉回复失败:", error);
    ElMessage.error("获取投诉回复失败");
  }
};

// 重置投诉回复表单
const resetReplyForm = () => {
  if (replyFormRef.value) {
    replyFormRef.value.resetFields();
  }

  replyForm.id = null;
  replyForm.afterSalesId = null;
  replyForm.complaintContent = "";
  replyForm.replyContent = "";
  replyForm.replyTime = "";
  replyForm.satisfactionLevel = 0;
};

// 提交投诉回复
const submitReply = async () => {
  if (!replyFormRef.value) return;

  try {
    const valid = await replyFormRef.value.validate();
    if (!valid) return;

    // 设置回复时间
    replyForm.replyTime = formatToLocalDateTime(new Date());

    let response;
    if (replyForm.id) {
      // 更新回复
      response = await updateComplaintReply(replyForm);
    } else {
      // 新增回复
      response = await addComplaintReply(replyForm);
    }

    if (response.success) {
      ElMessage.success(replyForm.id ? "更新回复成功" : "提交回复成功");
      replyDialogVisible.value = false;
      fetchRecordsrList(); // 刷新列表
    } else {
      ElMessage.error(response.message || "操作失败");
    }
  } catch (error) {
    console.error("提交投诉回复失败:", error);
    ElMessage.error("提交投诉回复失败");
  }
};

// 提交满意度评价
const submitSatisfaction = async () => {
  if (!replyForm.id || replyForm.satisfactionLevel <= 0) {
    ElMessage.warning("请先评分");
    return;
  }

  try {
    const response = await submitSatisfactionRating({
      id: replyForm.id,
      rating: replyForm.satisfactionLevel,
    });

    if (response.success) {
      ElMessage.success("提交评价成功");
      replyDialogVisible.value = false;
      fetchRecordsrList(); // 刷新列表
    } else {
      ElMessage.error(response.message || "操作失败");
    }
  } catch (error) {
    console.error("提交评价失败:", error);
    ElMessage.error("提交评价失败");
  }
};

// 删除售后服务
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除客户 "${row.customerName}"的售后服务信息吗？`, "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const response = await deleteAfterSalesRecords([row.id]);
    if (response.success) {
      ElMessage.success("删除成功");
      fetchRecordsrList();
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除售后服务失败:", error);
    }
  }
};

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请选择要删除的售后服务");
    return;
  }

  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 个售后服务信息吗？`, "警告", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    const response = await deleteAfterSalesRecords(selectedRows.value.map((row) => row.id));
    if (response.success) {
      ElMessage.success("批量删除成功");
      fetchRecordsrList();
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("批量删除售后服务失败:", error);
    }
  }
};

// 导出
const handleExport = async () => {
  await getServiceRecordListExcel();
  ElMessage.success("导出成功");
};

// 提交表单
const submitForm = async () => {
  if (!serviceFormRef.value) return;

  try {
    const valid = await serviceFormRef.value.validate();
    if (!valid) return;

    let response;
    response = await updateAfterSalesRecord(serviceForm);

    if (response.success) {
      ElMessage.success("更新成功");
      dialogVisible.value = false;
      fetchRecordsrList();
    }
  } catch (error) {
    console.error("更新售后服务失败:", error);
  }
};

// 重置表单
const resetForm = () => {
  if (serviceFormRef.value) {
    serviceFormRef.value.resetFields();
  }
  Object.keys(serviceForm).forEach((key) => {
    if (key === "id") {
      serviceForm[key] = null;
    } else if (key === "customerName") {
      serviceForm[key] = "";
    } else {
      serviceForm[key] = 0;
    }
  });
};
</script>

<style scoped>
.page-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

/* 搜索过滤区样式 */
.search-card {
  margin-bottom: 16px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

/* 表格工具栏 */
.table-toolbar {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

/* 表格区域 */
.table-card {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

:deep(.el-table__header) {
  background-color: #f5f7fa;
}

:deep(.el-table__header-wrapper th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 600;
  height: 50px;
}

:deep(.el-table__row td) {
  padding: 10px 0;
}

/* 分页容器 */
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 弹窗样式 */
:deep(.el-dialog) {
  border-radius: 8px;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #f0f0f0;
  padding: 15px 20px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid #f0f0f0;
  padding: 15px 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

/* 标签样式 */
:deep(.el-tag) {
  border-radius: 4px;
  padding: 0 10px;
  height: 28px;
  line-height: 28px;
}

/* 评分样式 */
:deep(.el-rate) {
  display: inline-flex;
  line-height: 1;
}

:deep(.el-rate__text) {
  margin-left: 10px;
  font-size: 14px;
}

:deep(.el-rate__icon) {
  font-size: 24px;
  margin-right: 6px;
}
</style>
